//
//  VCommunityViewController.m
//  QuickReadComic
//
//  Created by 苗钧豪 on 16/8/26.
//  Copyright © 2016年 苗钧豪. All rights reserved.
//

#import "VCommunityViewController.h"
#import "VView.h"
#import "JHAccountTool.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "ZWYNetTool.h"
#import "CommunityDataModel.h"
#import "CommunityUserModel.h"
#import "CommunityContentModel.h"
#import "FeedsModel.h"
#import "VTableViewCell.h"
#import "JHAccountTool.h"
#import "LoginViewController.h"
#import "MJRefresh.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "ImageViewController.h"
#import "MineViewController.h"
@interface VCommunityViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property(nonatomic,strong)NSArray *SegmentArray;// 分块数组
@property(nonatomic,strong)UISegmentedControl *segment;// 分块
@property(nonatomic,strong)UIScrollView *mainScrollView;// 主滚动视图
@property(nonatomic,strong)UIScrollView *squareScrollView;// 广场滚动视图
@property(nonatomic,strong)UIScrollView *hotAndNewScrollView;// 最热和最新分类滚动视图
@property(nonatomic,strong)NSArray *hotAndNewArray;// 分类数组
@property(nonatomic,strong)CommunityDataModel *model;
@property(nonatomic,strong)CommunityDataModel *model2;
@property(nonatomic,strong)NSMutableArray *Array;
@property(nonatomic,strong)VTableViewCell *cell;
@property(nonatomic,assign)CGFloat number;
@property(nonatomic,assign)NSInteger hotandnew;
@property(nonatomic,strong)UIButton *btn;
@end

@implementation VCommunityViewController
- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    [self createView];
    UITableView *tableview = [self.squareScrollView viewWithTag:0];
    tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [ZWYNetTool GET:@"http://api.kuaikanmanhua.com/v1/feeds/feed_lists?catalog_type=2&page_num=1&since=0&uid=0" andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
            self.model = [CommunityDataModel modelWithDic:result[@"data"]];
            [tableview reloadData];
        } andFailureBlock:^(NSError *error) {
            
        }];
        [tableview.mj_header endRefreshing];
    }];
    UITableView *tableviews = [self.squareScrollView viewWithTag:1];
    tableviews.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [ZWYNetTool GET:@"http://api.kuaikanmanhua.com/v1/feeds/feed_lists?catalog_type=2&page_num=1&since=0&uid=0" andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
            self.model = [CommunityDataModel modelWithDic:result[@"data"]];
            [tableviews reloadData];
        } andFailureBlock:^(NSError *error) {
            
        }];
        [tableviews.mj_header endRefreshing];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.Array = [NSMutableArray array];
    // 设置导航栏不透明
    self.navigationController.navigationBar.translucent = NO;
    [self square];
    [self setUp];
    [self NetWork];
}
- (void)NetWork {
    [ZWYNetTool GET:@"http://api.kuaikanmanhua.com/v1/feeds/feed_lists?catalog_type=2&page_num=1&since=0&uid=0" andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        self.model = [CommunityDataModel modelWithDic:result[@"data"]];
        [self.tableview reloadData];
    } andFailureBlock:^(NSError *error) {
        
    }];
    
    [ZWYNetTool GET:@"http://api.kuaikanmanhua.com/v1/feeds/feed_lists?catalog_type=1&page_num=1&since=0&uid=0" andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        self.model2 = [CommunityDataModel modelWithDic:result[@"data"]];
        [self.tableview reloadData];
    } andFailureBlock:^(NSError *error) {
        
    }];
}
// 封装UISegmentedControl
- (void)setUp {
    self.SegmentArray = [NSArray arrayWithObjects:@"关注",@"广场", nil];
    // 分块控件
    self.segment = [[UISegmentedControl alloc]initWithItems:_SegmentArray];
    // 布局
    self.segment.frame = CGRectMake(0, 0, 140, 30);
    // 倒圆角
    CALayer *layer = self.segment.layer;
    [layer setMasksToBounds:YES];
    [layer setCornerRadius:15];
    // 初始偏移量
    self.segment.selectedSegmentIndex = 1;
    // 控件颜色
    self.segment.tintColor = [UIColor colorWithRed:0.953 green:0.651 blue:0.075 alpha:1.000];
    // 控件方法
    [self.segment addTarget:self action:@selector(segmentAction) forControlEvents:(UIControlEventValueChanged)];
    // 设置为导航栏头视图
    self.navigationController.navigationBar.topItem.titleView = _segment;
}
// **************************关注界面
- (void)createView {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSInteger num = [user integerForKey:@"isLogin"];
    if (num == 0) {
        UIView *followView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        // 背景颜色
        followView.backgroundColor = [UIColor colorWithWhite:0.940 alpha:1.000];
        // 图片控制器
        UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width / 2 - 100, 150, 200, 150)];
        // 图片
        imgview.image = [UIImage imageNamed:@"5"];
        // 添加到followView
        [followView addSubview:imgview];
        // 登录按钮
        UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        // 按钮title
        [loginBtn setTitle:@"立即登录" forState:(UIControlStateNormal)];
        // 文字颜色
        [loginBtn setTitleColor:[UIColor colorWithRed:0.529 green:0.447 blue:0.173 alpha:1.000] forState:(UIControlStateNormal)];
        // 按钮布局
        loginBtn.frame = CGRectMake(self.view.bounds.size.width / 2 - 60, 370, 120, 50);
        // 倒圆角
        CALayer *layer = loginBtn.layer;
        [layer setMasksToBounds:YES];
        [layer setCornerRadius:25];
        // 背景颜色
        loginBtn.backgroundColor = [UIColor colorWithRed:0.973 green:0.827 blue:0.314 alpha:1.000];
        // 按钮方法
        [loginBtn addTarget:self action:@selector(motal) forControlEvents:(UIControlEventTouchUpInside)];
        // 添加到followView
        [followView addSubview:loginBtn];
        [self.mainScrollView addSubview:followView];
    } else {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:(UITableViewStylePlain)];
        tableView.delegate = self;
        tableView.dataSource = self;
        [tableView registerNib:[UINib nibWithNibName:@"VTableViewCell" bundle:nil] forCellReuseIdentifier:@"VCell"];
        [self.mainScrollView addSubview:tableView];

    }
}
- (void)motal {
    // 模态弹出登录界面
    LoginViewController *LoginVC = [[LoginViewController alloc]init];
    UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:LoginVC];
    [self presentViewController:nvc animated:YES completion:nil];
}
// **************************广场界面
- (void)square {
    // 主滚动视图布局
    self.mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    self.mainScrollView.delegate = self;
    // 偏移量
    _mainScrollView.contentOffset = CGPointMake(self.view.bounds.size.width, 0);
    _mainScrollView.pagingEnabled = YES;
    // 滚动范围
    _mainScrollView.contentSize = CGSizeMake(self.view.bounds.size.width * 2, self.view.bounds.size.height);
    // 添加到self.view
    [self.view addSubview:self.mainScrollView];
    // 初始化数组
    self.hotAndNewArray = [NSArray arrayWithObjects:@"热门",@"最新", nil];
    // 分类滚动视图布局
    self.hotAndNewScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width, 0, self.view.bounds.size.width, 30)];
    // 偏移量
    _hotAndNewScrollView.contentOffset = CGPointMake(0, 0);
    // 滚动范围
    _hotAndNewScrollView.contentSize = CGSizeMake(self.view.bounds.size.width, 30);
    // 循环创建button
    for (int i = 0; i < 2; i ++) {
        _btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        // 文字内容
        [_btn setTitle:[NSString stringWithFormat:@"%@",_hotAndNewArray[i]] forState:(UIControlStateNormal)];
        // 文字颜色
        [_btn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        _btn.tag = i;
        // 布局
        _btn.frame = CGRectMake(self.view.bounds.size.width / 2 * i, 0, self.view.bounds.size.width / 2, 30);
        [_btn addTarget:self action:@selector(offset:) forControlEvents:(UIControlEventTouchUpInside)];
        // 添加到滚动视图
        [_hotAndNewScrollView addSubview:_btn];
    }
    [_mainScrollView addSubview:_hotAndNewScrollView];
    // 广场数组布局
    self.squareScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width, 30, self.view.bounds.size.width, self.view.bounds.size.height - 30)];
    _squareScrollView.pagingEnabled = YES;
    _squareScrollView.contentOffset = CGPointMake(0, 0);
    _squareScrollView.contentSize = CGSizeMake(self.view.bounds.size.width * 2, self.view.bounds.size.height);
    for (int i = 0; i < 2; i ++) {
        UITableView *tableview = [[UITableView alloc]initWithFrame:CGRectMake(i * self.view.bounds.size.width, 0, self.view.bounds.size.width, self.view.bounds.size.height - 140) style:(UITableViewStylePlain)];
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.estimatedRowHeight = 1000;
        tableview.rowHeight = UITableViewAutomaticDimension;
        tableview.tag = i;
        [tableview registerNib:[UINib nibWithNibName:@"VTableViewCell" bundle:nil] forCellReuseIdentifier:@"VCell"];
        [_squareScrollView addSubview:tableview];
    }
    [_mainScrollView addSubview:_squareScrollView];
}
- (void)offset:(UIButton *)button {
    if (button.tag == 1) {
        [self.squareScrollView setContentOffset:CGPointMake(self.view.bounds.size.width, 0) animated:YES];
    } else {
        [self.squareScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeMake(0, 0);
    if (tableView.tag == 0) {
        FeedsModel *feeds = self.model.feeds[indexPath.row];
        NSString *content = feeds.content.text;
        CGSize size = [content sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(self.view.bounds.size.width, 1000.0) lineBreakMode:(UILineBreakModeWordWrap)];
        return size.height + 100;
    } else if (tableView.tag == 1) {
        FeedsModel *feeds = self.model2.feeds[indexPath.row];
        NSString *content = feeds.content.text;
        CGSize size = [content sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(self.view.bounds.size.width, 1000.0) lineBreakMode:(UILineBreakModeWordWrap)];
        return size.height + 100;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 0) {
        self.
        cell = [tableView dequeueReusableCellWithIdentifier:@"VCell" forIndexPath:indexPath];
        FeedsModel *feeds = self.model.feeds[indexPath.row];
        _cell.contentLabel.text = feeds.content.text;
        UIImageView *imgview = [[UIImageView alloc]init];
        [imgview sd_setImageWithURL:[NSURL URLWithString:feeds.user.avatar_url]];
        [_cell.headerBtn setBackgroundImage:imgview.image forState:(UIControlStateNormal)];
        [_cell.nameBtn setTitle:feeds.user.nickname forState:(UIControlStateNormal)];
        [_cell.goodBtn setTitle:[NSString stringWithFormat:@"%ld",(long)feeds.likes_count] forState:(UIControlStateNormal)];
        [_cell.sayBtn setTitle:[NSString stringWithFormat:@"%ld",(long)feeds.comments_count] forState:(UIControlStateNormal)];
        NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a = [dat timeIntervalSince1970] * 1000;
        NSString *timeString = [NSString stringWithFormat:@"%.0f",a];
        NSLog(@"当前时间戳%@",timeString);
        NSInteger nowtime = [timeString intValue];
        if (feeds.created_at <= nowtime - 86400) {
            _cell.dateLabel.text = @"更久";
        } else {
            NSString *time = [self timeWithTimeIntervalString2:[NSString stringWithFormat:@"%ld",(long)feeds.created_at]];
            NSLog(@"当前时间%@",time);
            _cell.dateLabel.text = time;
        }
        _cell.feeds = feeds;
        [_cell assignment];
        return _cell;
    } else if (tableView.tag == 1) {
        self.
        cell = [tableView dequeueReusableCellWithIdentifier:@"VCell" forIndexPath:indexPath];
        FeedsModel *feeds = self.model2.feeds[indexPath.row];
        _cell.contentLabel.text = feeds.content.text;
        UIImageView *imgview = [[UIImageView alloc]init];
        [imgview sd_setImageWithURL:[NSURL URLWithString:feeds.user.avatar_url]];
        [_cell.headerBtn setBackgroundImage:imgview.image forState:(UIControlStateNormal)];
        [_cell.nameBtn setTitle:feeds.user.nickname forState:(UIControlStateNormal)];
        [_cell.goodBtn setTitle:[NSString stringWithFormat:@"%ld",(long)feeds.likes_count] forState:(UIControlStateNormal)];
        [_cell.sayBtn setTitle:[NSString stringWithFormat:@"%ld",(long)feeds.comments_count] forState:(UIControlStateNormal)];
        NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a = [dat timeIntervalSince1970] * 1000;
        NSString *timeString = [NSString stringWithFormat:@"%.0f",a];
        NSLog(@"当前时间戳%@",timeString);
        NSInteger nowtime = [timeString intValue];
        if (feeds.created_at <= nowtime - 86400) {
            _cell.dateLabel.text = @"更久";
        } else {
            NSString *time = [self timeWithTimeIntervalString2:[NSString stringWithFormat:@"%ld",(long)feeds.created_at]];
            NSLog(@"当前时间%@",time);
            _cell.dateLabel.text = time;
        }
        _cell.feeds = feeds;
        [_cell assignment];
        return _cell;
    }
    return nil;
}
- (NSString *)timeWithTimeIntervalString2:(NSString *)timeString2
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"HH:mm"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString2 doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
// 分块控件方法
- (void)segmentAction {
    if (self.segment.selectedSegmentIndex == 0) {
        // 控制滚动视图偏移量
        self.mainScrollView.contentOffset = CGPointMake(0, 0);
    } else if (self.segment.selectedSegmentIndex == 1) {
        self.mainScrollView.contentOffset = CGPointMake(self.view.bounds.size.width, 0);
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_mainScrollView.contentOffset.x == 0) {
        self.segment.selectedSegmentIndex = 0;
    } else if (_mainScrollView.contentOffset.x == self.view.bounds.size.width) {
        self.segment.selectedSegmentIndex = 1;
    }
    
    if (_squareScrollView.contentOffset.x == 0) {
        if (_btn.tag == 0) {
            [_btn setTitleColor:[UIColor colorWithRed:0.953 green:0.651 blue:0.075 alpha:1.000] forState:(UIControlStateNormal)];
        }
        if (_btn.tag == 1) {
            [_btn setTitleColor:[UIColor grayColor]forState:(UIControlStateNormal)];
        }
    } else if (_squareScrollView.contentOffset.x == self.view.bounds.size.width) {
        if (_btn.tag == 1) {
            [_btn setTitleColor:[UIColor colorWithRed:0.953 green:0.651 blue:0.075 alpha:1.000] forState:(UIControlStateNormal)];
        }
        if (_btn.tag == 0) {
            [_btn setTitleColor:[UIColor grayColor]forState:(UIControlStateNormal)];
        }
    }
//    /****************滑动到顶部****************/
//    CGPoint offset = scrollView.contentOffset;
//    CGRect bounds = scrollView.bounds;
//    CGSize size = scrollView.contentSize;
//    UIEdgeInsets inset = scrollView.contentInset;
//    CGFloat currentOffset = offset.y + bounds.size.height - inset.bottom;
//    CGFloat maximumOffset = size.height;
//    CGFloat minimumOffset = 527;
//    NSLog(@"\n%f\n%f\n",currentOffset,maximumOffset);
//    if(currentOffset < minimumOffset ) {
//        NSLog(@"-----我要刷新数据-----");
//        [self.tableview.mj_header beginRefreshing];
//    }
}
#pragma mark ================ 跳转 ================
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView.tag == 0) {
        FeedsModel *feeds = self.model.feeds[indexPath.row];
        ImageViewController *ivc = [[ImageViewController alloc]init];
        ivc.imageNumber = feeds.content.images.count;
        ivc.imagesArray = feeds.content.images;
        ivc.urlString = feeds.content.image_base;
        ivc.feeds = feeds;
        UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:ivc];
        [self presentViewController:navc animated:YES completion:nil];
    } else if (tableView.tag == 1) {
        
    }
    
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
